﻿
//

//


namespace Admin.NET.Core.JsonMapping;

using System.Collections.Generic;
using System.Text.RegularExpressions;

public static class JsonPathHelper
{
    public enum PathPartType
    {
        Property,
        Index
    }

    public record PathPart(PathPartType Type, string Name = null, int Index = -1);

    /// <summary>
    /// 公共方法：解析 JSON 路径，如: user.name, orders[0].id
    /// </summary>
    public static List<PathPart> ParsePath(string path)
    {
        if (string.IsNullOrEmpty(path)) return new List<PathPart>();

        var parts = new List<PathPart>();
        var regex = new Regex(@"([a-zA-Z_]\w*)|\[(\d+|\*)\]", RegexOptions.Compiled);

        foreach (Match match in regex.Matches(path))
        {
            if (match.Groups[1].Success)
            {
                parts.Add(new PathPart(PathPartType.Property, Name: match.Groups[1].Value));
            }
            else if (match.Groups[2].Success)
            {
                int index = match.Groups[2].Value == "*" ? -1 : int.Parse(match.Groups[2].Value);
                parts.Add(new PathPart(PathPartType.Index, Index: index));
            }
        }

        return parts;
    }
}